import { useState } from "react";
import styles from './Chat.module.scss'

export default function ChatApp() {
    const [to, setTo] = useState<ContactsProps>(contacts[0])

    return (
        <div className={styles.chatDiv}>
            <ContactList contacts={contacts}
                onSelect={item => setTo(item)} />
            <Chat {...to} />
        </div>
    )
}

function ContactList({ contacts, onSelect }: { contacts: ContactsProps[], onSelect: (contact: ContactsProps) => void }) {
    return (
        <section>
            <ul className={styles.chatUl}>
                {contacts.map(item => <li key={item.email} className={styles.chatLi}>
                    <button className={styles.chatButton} onClick={() => { onSelect(item) }}>
                        {item.name}
                    </button>
                </li>)}
            </ul>
        </section>
    )
}

function Chat({ name, email }: ContactsProps) {
    const [text, setText] = useState<string>('')

    return (
        <section className={styles.chatBox}>
            <textarea
                className={styles.chatTextarea}
                value={text}
                placeholder={'Chat to ' + name}
                onChange={e => setText(e.target.value)}>
            </textarea>
            <br />
            <button>发送给 {email}</button>
        </section>
    )
}

interface ContactsProps {
    name: string
    email: string
}

const contacts: ContactsProps[] = [
    { name: 'Taylor', email: 'taylor@mail.com' },
    { name: 'Alice', email: 'alice@mail.com' },
    { name: 'Bob', email: 'bob@mail.com' }
];